package cn.openea.perpartner.payment.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.openea.perpartner.payment.web.points.dto.TokenVo;
import cn.openea.perpartner.payment.web.points.service.IValidateService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class PayPermissionInterceptor implements HandlerInterceptor {
	@Autowired
	private IValidateService validateService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		//获取请求body
		byte[] bodyBytes = StreamUtils.copyToByteArray(request.getInputStream());
		String body = new String(bodyBytes, request.getCharacterEncoding());
		TokenVo vo = new TokenVo();
		BeanUtil.copyProperties(JSON.parseObject(body), vo,true);
		if (!validateService.validateToken(vo)){
			response.getWriter().println("{\"code\":\"201\", \"msg\":\"token validate failed!\"}");
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

}
